package com.smart.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.smart.constants.SmartConstants;
import com.smart.dao.NoticeDAO;
import com.smart.model.AccessToken;
import com.smart.model.House;
import com.smart.model.MaintenanceManInfo;
import com.smart.model.Notice;
import com.smart.model.RepairRequest;
import com.smart.model.RepairRequestBriefInfo;
import com.smart.model.TextMessage;
import com.smart.model.UnverifiedUser;
import com.smart.model.User;
import com.smart.model.template.ArrearData;
import com.smart.model.template.ArrearTemplate;
import com.smart.model.template.Parameter;
import com.smart.service.NoticeService;
import com.smart.service.RepairRequestService;
import com.smart.service.UserService;
import com.smart.util.CheckUtil;
import com.smart.util.JsonUtil;
import com.smart.util.MessageUtil;
import com.smart.util.WeixinUtil;

@Controller
public class WeixinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	String name;

	public WeixinServlet() {
		super();
	}

	@RequestMapping(value = "/wechat/wx", method = RequestMethod.GET)
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("get请求");
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");

		System.out.println("hello");
		PrintWriter out = resp.getWriter();
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
	}

	@RequestMapping(value = "/wechat/wx", method = RequestMethod.POST)
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("post请求 ");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();
		try {
			Map<String, String> map = MessageUtil.xmlToMap(req);
			String ToUserName = map.get("ToUserName");
			String FromUserName = map.get("FromUserName");
			String CreateTime = map.get("CreateTime");
			String MsgType = map.get("MsgType");
			String Event = map.get("Event");
			String message = null;
			if ("event".equals(MsgType)) {
				if ("subscribe".equals(Event)) {
					System.out.println("subscribe");
					// message=MessageUtil.initMessgae(ToUserName,
					// FromUserName);
					
					/*
					User u = new User();
					u.setOpen_id(FromUserName);
					UserService userService = new UserService();
					try {
						System.out.println("add1");
						userService.add(u.getOpen_id());
						System.out.println("add2");
					} catch (SQLException e) {
						e.printStackTrace();
					}
					*/
					
					TextMessage text = new TextMessage();
					text.setFromUserName(ToUserName);
					text.setToUserName(FromUserName);
					text.setMsgType("text");
					text.setCreateTime(new Date().getTime() + "");
					text.setContent("谢谢您的关注！！！");
					message = MessageUtil.textMessageToXml(text);
					out.print(message);
				} else if ("unsubscribe".equals(Event))// 说明是unsubscribe
				{
					System.out.println("unsubscribe");
					/*
					User u = new User();
					u.setOpen_id(FromUserName);
					UserService userService = new UserService();
					try {
						System.out.println("add1");
						userService.del(u.getOpen_id());
						System.out.println("add2");
					} catch (SQLException e) {
						e.printStackTrace();
					}
				*/	
				} else {
					System.out.println("Event:" + Event);
				}
			} else if ("text".equals(MsgType)) {
				String Content = map.get("Content");
				/*
				if (Content.equals("1")) {
					TextMessage text = new TextMessage();
					text.setFromUserName(ToUserName);
					text.setToUserName(FromUserName);
					text.setMsgType("text");
					text.setCreateTime(new Date().getTime() + "");
					text.setContent("http://42.96.209.192/SmartCommunity/to_reg");
					message = MessageUtil.textMessageToXml(text);
					out.print(message);
				} else if (Content.equals("2")) {
					System.out.println("name:" + name);
				} else {
					name = Content;
				}
				*/
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/wechat/to_reg")
	public String to_register_page(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("turn to register page .....");
		String code = req.getParameter("code");
		String grant_type = req.getParameter("grant_type");
		System.out.println("code:" + code + "," + "grant_type:" + grant_type);
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		url = url.replace("APPID", SmartConstants.APPID).replace("SECRET", SmartConstants.APPSECRET)
				.replace("CODE", code);
		JSONObject jsonObject = WeixinUtil.doGetStr(url);
		String open_id = jsonObject.getString("openid");
		HttpSession session = req.getSession();
		System.out.println("session:" + session);
		String sessionId = session.getId();
		if (session.isNew())
			System.out.println("session create success,session id:" + sessionId);
		else
			System.out.println("server already have session,session id:" + sessionId);
		session.setAttribute("hello", "world");
		session.setAttribute("open_id", open_id);
		return "register";
	}

	@RequestMapping(value = "/wechat/web_authority")
	public void web_authority(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("web_authority method start....");
		HttpSession session=req.getSession();
		String code = req.getParameter("code");
		String grant_type = req.getParameter("grant_type");
		System.out.println("code:" + code + "," + "grant_type:" + grant_type);
		String url =SmartConstants.CODE_FOR_ACCESSTOKEN_URL;
		url = url.replace("APPID", SmartConstants.APPID).replace("SECRET", SmartConstants.APPSECRET)
				.replace("CODE", code);
		JSONObject jsonObject = WeixinUtil.doGetStr2(url);
		//获取到openid和access_token
		String openId = jsonObject.getString("openid");
		UserService userSer=new UserService();
		int verified=userSer.getVerifiedByOpenId(openId);
		session.setAttribute("verified",verified);
		String inform_access_token=jsonObject.getString("access_token");
		//进一步获取详细信息
		String inform_url="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		inform_url=inform_url.replace("ACCESS_TOKEN", inform_access_token).replace("OPENID", openId);
		jsonObject = WeixinUtil.doGetStr(inform_url);
		String nickname=jsonObject.getString("nickname");
		String sex=jsonObject.getString("sex");;
		String province=jsonObject.getString("province");
		String city=jsonObject.getString("city");
		String country=jsonObject.getString("country");
		//用户头像的url
		String headimgurl=jsonObject.getString("headimgurl");
		session.setAttribute("headimgurl",headimgurl);
		session.setAttribute("openId",openId);
		session.setAttribute("nickname",nickname);
	    session.setAttribute("sex",sex);
	    session.setAttribute("province",province);
		session.setAttribute("city",city);
		session.setAttribute("country",country);
		System.out.println("openId:"+session.getAttribute("openId"));
		System.out.println("headimgurl:"+session.getAttribute("headimgurl"));
		try {
			resp.sendRedirect("/SmartCommunity/views/wechat/home.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("web_authority method finish....");
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("start register");
		Cookie[] cookies = req.getCookies();
		// 如果用户是第一次访问，那么得到的cookies将是null
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				System.out.println("name:" + cookie.getName() + ",value:" + cookie.getValue());
			}
		}
		HttpSession session = req.getSession();
		System.out.println("session:" + session);
		String sessionId = session.getId();
		if (session.isNew())
			System.out.println("session create success,session id:" + sessionId);
		else
			System.out.println("server already have session,session id:" + sessionId);
		String nickname = req.getParameter("username");
		String telphone_num = req.getParameter("mobile_phone");
		int building_id = Integer.parseInt(req.getParameter("building_no").charAt(0) + "");
		int room_no = Integer.parseInt(req.getParameter("room_no"));
		String hello = session.getAttribute("hello").toString();
		String open_id = session.getAttribute("open_id").toString();
		System.out.println("hello:" + hello);
		System.out.println("openid:" + open_id);
		System.out.println("nickname:" + nickname + "," + "telphonenum:" + telphone_num + "," + "building_id:"
				+ building_id + "," + "room_no:" + room_no);
		User user = new User();
		user.setUserName(nickname);
		user.setOpenID(open_id);
		user.setPhone(telphone_num);
		user.setVerified(1);
		House house = new House();
		house.setBuilding_id(building_id);
		house.setRoom_no(room_no);
		UserService userSer = new UserService();
		if (userSer.userReg(house, user))
				System.out.println("register success");
		else
				System.out.println("register failed");
		return "home";
	}

	@RequestMapping(value = "/get_unverified_user_info", method = RequestMethod.POST)
	public void getUnverifiedUserInfo(HttpServletRequest req, HttpServletResponse resp) {
		UserService userSer = new UserService();
		PrintWriter pw = null;
		resp.setCharacterEncoding("UTF-8");
		try {
			pw = resp.getWriter();
			List<UnverifiedUser> userList = userSer.getUnverifiedUser();
			String json = JsonUtil.toJson(userList);
			pw.print(json);
			pw.flush();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void updateUserVerifyStatus(HttpServletRequest req, HttpServletResponse resp) {
		UserService userSer = new UserService();
		PrintWriter pw = null;

	}

	@RequestMapping(value = "/inform", method = RequestMethod.POST)
	public String inform(HttpServletRequest req, HttpServletResponse resp) {
		try {
			req.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String message = req.getParameter("message");
		System.out.println("inform.");
		System.out.println("message is " + message);
		WeixinUtil.sendAll(message);
		return "send";// ?success=1";
	}
}
